'''
Created on Nov 20, 2011

@author: Jonathan Herbst
'''

import APIRequest
import JinjaTemplate

import Model.Game
import Model.Settings

import webapp2

class Game(APIRequest.XMLAPIRequest, JinjaTemplate.JinjaTemplate):
    
    _parameterDefinitions = [APIRequest.Integer32("page", default=0, lowerBound=0),
                             APIRequest.String("gameId")]
    
    def __init__(self, request, response):
        APIRequest.XMLAPIRequest.__init__(self, request, response)
        JinjaTemplate.JinjaTemplate.__init__(self, "Games.xml")
    
    def get(self):
        if self._parameters.gameId:
            self._context["games"] = [Model.Game.Game.get(self._parameters.gameId)]
        else:  
            q = Model.Game.Game.all()
            self._context["games"] = q.fetch(Model.Settings.REQUEST_LIMIT,
                                             Model.Settings.REQUEST_LIMIT * self._parameters.page)
        self.response.out.write(self.render())
        
class Paper(APIRequest.XMLAPIRequest, JinjaTemplate.JinjaTemplate):
    _parameterDefinitions = [APIRequest.String("gameId", required=True),
                             APIRequest.String("pageId"),
                             APIRequest.Integer32("page", default=0, lowerBound=0)]
    
    def __init__(self, request, response):
        APIRequest.XMLAPIRequest.__init__(self, request, response)
        JinjaTemplate.JinjaTemplate.__init__(self, "Papers.xml")
        
    def get(self):
        game = Model.Game.Game.get(self._parameters.gameId)
        if self._parameters.paperId:
            self._context["papers"] = [Model.Paper.Paper.get(self._parameters.paperId)]
            if self._context["papers"].game != game.key():
                raise Model.Error.NotFound()
        else:
            self._context["papers"] = game.paper.fetch(Model.Settings.REQUEST_LIMIT,
                                                       Model.Settings.REQUEST_LIMIT * self._parameters.page)
        self.response.out.write(self.render())
        
class Item(APIRequest.XMLAPIRequest, JinjaTemplate.JinjaTemplate):
    _parameterDefinitions = [APIRequest]
        
class StartGame(APIRequest.APIRequest):
    def get(self):
        self.post()
    
    def post(self):
        game = Model.Game.Game()
        game.put()
    
class AddItem(webapp2.RequestHandler):
    def post(self):
        pass
    
app = webapp2.WSGIApplication(
    [('/startgame', StartGame),
     ('/game', Game)],
    debug=True
    )